using System.Collections.Generic;
using System.Linq;
using YoYoMooc.StudentManagement.Models;

namespace YoYoMooc.StudentManagement.Services.Services
{
    public class MockStudentRepository : IStudentRepository
    {
        private readonly List<Student> _studentList;

        public MockStudentRepository()
        {
            _studentList = new List<Student>()
            {
                 new Student() { Id = 1, Name = "张三", Major = MajorEnum.ComputerScience, Email = "Tony-zhang@52abp.com" },
            new Student() { Id = 2, Name = "李四", Major = MajorEnum.ElectronicCommerce, Email = "lisi@52abp.com" },
            new Student() { Id = 3, Name = "王二麻子", Major = MajorEnum.Mathematics, Email = "wang@52abp.com" },
            };
        }

        public IEnumerable<Student> Search(string searchTerm)
        {
            if (string.IsNullOrEmpty(searchTerm))
            {
                return _studentList;
            }
          

            var dtos = _studentList.Where(e => e.Name.Contains(searchTerm) ||
                                             e.Email.Contains(searchTerm)).ToList();
            return dtos;
        }

        public IEnumerable<Student> GetAllStudents()
        {
            return _studentList;
        }

        public Student GetStudent(int id)
        {
            return _studentList.FirstOrDefault(e => e.Id == id);
        }

        public Student Update(Student updatedStudent)
        {
            Student student = _studentList
                   .FirstOrDefault(e => e.Id == updatedStudent.Id);
            if (student != null)
            {
                student.Name = updatedStudent.Name;
                student.Email = updatedStudent.Email;
                student.Major = updatedStudent.Major;
                student.PhotoPath = updatedStudent.PhotoPath;
            }
            return student;
        }

        public Student Add(Student newStudent)
        {
            newStudent.Id = _studentList.Max(s => s.Id) + 1;

            _studentList.Add(newStudent);
            return newStudent;

        }

        public Student Delete(int id)
        {
            var studentToDelete = _studentList.FirstOrDefault(e => e.Id == id);

            if (studentToDelete != null)
            {
                _studentList.Remove(studentToDelete);
            }

            return studentToDelete;
        }

        public IEnumerable<MajorHeadCount> StudentCountByMajorEnum(MajorEnum? major)
        {
            IEnumerable<Student> query = _studentList;


            if (major.HasValue)
            {
                query = query.Where(a => a.Major == major.Value);
            }



            var dtos = query.GroupBy(e => e.Major)
                .Select(g => new MajorHeadCount()
                {
                    Major = g.Key.Value,
                    Count = g.Count()
                }).ToList();

            return dtos;
        }
    }
}